package com.baidu.iit.pxp.parser;

import com.baidu.iit.pxp.constants.BpmnXMLConstants;
import com.baidu.iit.pxp.model.EventSubProcess;
import com.baidu.iit.pxp.model.SubProcess;
import com.baidu.iit.pxp.model.Transaction;
import com.baidu.iit.pxp.model.Process;
import com.baidu.iit.pxp.util.BpmnXMLUtil;
import org.apache.commons.lang3.StringUtils;

import javax.xml.stream.XMLStreamReader;
import java.util.List;

/**
 *
 * 子流程定义解析
 * User: huangweili
 * Date: 14-4-26
 * Time: 下午2:07
 */
public class SubProcessParser {

    public void parse(XMLStreamReader xtr, List<SubProcess> activeSubProcessList, Process activeProcess) {
        SubProcess subProcess = null;
        if (BpmnXMLConstants.ELEMENT_TRANSACTION.equalsIgnoreCase(xtr.getLocalName())) {
            subProcess = new Transaction();
        } else if (BpmnXMLConstants.ATTRIBUTE_VALUE_TRUE.equalsIgnoreCase(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_TRIGGERED_BY))) {
            subProcess = new EventSubProcess();
        } else {
            subProcess = new SubProcess();
        }
        BpmnXMLUtil.addXMLLocation(subProcess, xtr);
        activeSubProcessList.add(subProcess);

        subProcess.setId(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_ID));
        subProcess.setName(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_NAME));

        boolean async = false;
        String asyncString = xtr.getAttributeValue(BpmnXMLConstants.ACTIVITI_EXTENSIONS_NAMESPACE, BpmnXMLConstants.ATTRIBUTE_ACTIVITY_ASYNCHRONOUS);
        if (BpmnXMLConstants.ATTRIBUTE_VALUE_TRUE.equalsIgnoreCase(asyncString)) {
            async = true;
        }

        boolean notExclusive = false;
        String exclusiveString = xtr.getAttributeValue(BpmnXMLConstants.ACTIVITI_EXTENSIONS_NAMESPACE, BpmnXMLConstants.ATTRIBUTE_ACTIVITY_EXCLUSIVE);
        if (BpmnXMLConstants.ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(exclusiveString)) {
            notExclusive = true;
        }

        subProcess.setAsynchronous(async);
        subProcess.setNotExclusive(notExclusive);
        if(StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_DEFAULT))) {
            subProcess.setDefaultFlow(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_DEFAULT));
        }

        if(activeSubProcessList.size() > 1) {
            activeSubProcessList.get(activeSubProcessList.size() - 2).addFlowElement(subProcess);

        } else {
            activeProcess.addFlowElement(subProcess);
        }
    }


}
